package com.maning.mndialoglibrary;


import com.maning.mndialoglibrary.config.MToastConfig;
import com.maning.mndialoglibrary.utils.TextUtils;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

import java.lang.reflect.InvocationTargetException;


/**
 * Created by maning on 2017/8/11.
 * 自定义Toast
 */

public class MToast {

    private static ToastDialog currentToast;


    public static void makeTextLong(Context context, CharSequence message, MToastConfig config) {
        getToast(config, context, message, 2000).show();
    }

    public static void makeTextShort(Context context, CharSequence message, MToastConfig config) {
        getToast(config, context, message, 1000).show();
    }

    //----对外提供方法---------

    private static ToastDialog getToast(MToastConfig config, Context context, CharSequence message, int duration) {
        if(currentToast==null){
            currentToast=new ToastDialog(context);
            currentToast.setTransparent(true);
        }
        LayoutScatter inflater = LayoutScatter.getInstance(context);
        Component toastLayout = inflater.parse(ResourceTable.Layout_mn_toast_layout, null,false);

        Text tvShowToast = (Text) toastLayout.findComponentById(ResourceTable.Id_tvShowToast);
        tvShowToast.setText(message.toString());
        tvShowToast.setTextSize((int) config.toastTextSize);
        Image ivLeftShow = (Image) toastLayout.findComponentById(ResourceTable.Id_ivLeftShow);
        if(config.toastIcon!=null){
            ivLeftShow.setImageElement(config.toastIcon);
        }else{
            ivLeftShow.setVisibility(Component.HIDE);
        }

        DirectionalLayout toastBackgroundView = (DirectionalLayout) toastLayout.findComponentById(ResourceTable.Id_toastBackgroundView);
        currentToast.setComponent(toastLayout);

        RgbColor rgbColor=config.toastBackgroundColor;
        ShapeElement element = new ShapeElement();
        if(rgbColor!=null){
            element.setRgbColor(rgbColor);
            toastBackgroundView.setBackground(element);
        }

        currentToast.setAlignment(config.toastGravity);
        currentToast.setOffset(0,300);
        if(duration>0){
            currentToast.setAutoClosable(true);
        }
        currentToast.setDuration(duration);

        return currentToast;
    }
}
